<?php

include 'bur_controller.php';

class Detail_payment extends Bur_controller {

	function index()
	{
		$this->view();
	}
		
	function _report_meta($nim, $bulan, $semester)
	{

		$nama = $this->_name($nim);
		$angkatan = $this->_peer_year($nim);
		$tahun_ajaran = $this->_acd_year_desc_from_semester($semester);
		
		$tanggal = mdate("%d/%m/%Y", now());;
		$penerima = '';		
		
		return array(
			'nim' => $nim,
			'nama' => $nama,
			'tahun_ajaran' => $tahun_ajaran,
			'angkatan' => $angkatan,		
			'tanggal' => $tanggal,
			'penerima' => $penerima,			
		);
	}
	
	function _report($nim, $bulan, $semester, $n_copy)
	{
		return array(
			'n_copy' => $n_copy,	
			'meta' => $this->_report_meta($nim, $bulan, $semester),
			'data' => $this->_payment_plan_data($nim, $bulan, $semester),			
		);
	}
	
	function batch_report($type = 'csv', $n_copy = 1, $bulan = NULL, $semester = NULL)
	{
		// this function receives array of NIM from $_POST['students']				
		if (is_null_or_false($n_copy)) {
			$n_copy = 2;
		}
		
		if (is_null_or_false($bulan)) {
			$bulan = $this->_current_month();
		}
		
		if (is_null_or_false($semester)) {
			$semester = $this->_current_semester();
		}
		
		$students = $this->input->post('students');
		
		if (!$students) {
			$students = $this->_students_with_processed_plan_id($bulan, $semester);
		}		
		if ($type == 'csv') {
			$fields = array();
			$data = array();
			foreach($students as $idx => $nim) {				
				$record = $this->_report($nim, $bulan, $semester, $n_copy);
				
				if (is_empty($record['data']['tabel'])) continue;
				
				if (is_empty($fields)) {
					$fields[] = 'NIM';
					$fields[] = 'Nama';
					foreach ($record['data']['tabel'] as $val) {
						$fields[] = $val['biaya'];
					}
					$fields[] = 'Total';
				}
				
				$_data = array();
				$_data[] = $record['meta']['nim'];
				$_data[] = $record['meta']['nama'];
				
				$sum = 0;
				foreach ($record['data']['tabel'] as $val) {
					$_data[] = $val['rp'];
					$sum += $val['rp'];
				}
				$_data[] = $sum;
							
				$data[] = $_data;
			}
			
		
			$sum = array();
			foreach ($fields as $val) {
				if ($val=='NIM') {
					$sum[] = '';
				} else if ($val=='Nama') {
					$sum[] = 'Total';
				} else {
					$sum[] = 0;
				}
			}
						
			foreach ($data as $row) {
				$j = 0;
				foreach ($row as $col) {
					if ($j>1) {
						$sum[$j] += $col;
					}
					$j++;
				}
			}

			$data[] = $sum;			
			
			foreach ($data as $ridx => $row) {
				$j = 0;
				foreach ($row as $cidx => $col) {
					if ($j>1) {
						$data[$ridx][$cidx] = number_format($col, 2);
					}
					$j++;
				}
			}
					
			$filename = 'bursar_'.$semester.'_'.$bulan;
			$filename .= '_'.now();
			$filename .= '.csv';

			$file = generate_csv($fields, $data);
			force_download($filename, $file); 
		}
	}

}
